//
//  TimDataManager.swift
//  TimMusic
//
//  Created by nkl on 2024/10/25.
//

import Foundation
import SwiftUI
class TimDataManager {
    static let shared: TimDataManager = .init()

    func fetchItemModel(id: String) -> MyWidgetItemModel? {
        if let model = fetchMyWidgets() {
            return model.datas.first(where: { mMd in
                mMd.uidString == id
            })
        }
        return nil
    }

    func fetchSmallWidgets() -> [MyWidgetItemModel] {
        if let model = fetchMyWidgets() {
            return model.datas.filter {
                $0.itemModel.type == .small
            }
        }
        return []
    }

    func fetchMediumWidgets() -> [MyWidgetItemModel] {
        if let model = fetchMyWidgets() {
            return model.datas.filter {
                $0.itemModel.type == .medium
            }
        }
        return []
    }

    func deleteMyWidget(id: String, complete: (Bool) -> Void) {
        if let dataModel = fetchMyWidgets() {
            var newModel = dataModel
            newModel.datas.removeAll {
                $0.uidString == id
            }
            if let newData = TimData.codeModel(from: newModel) {
                let dataSaver = UserDefaults(suiteName: TimeGroupName)
                dataSaver?.set(newData, forKey: TimWidgetKey)
                complete(true)
            } else {
                complete(false)
            }
        } else {
            complete(false)
        }
    }

    func fetchMyWidgets() -> MyWidgetsModel? {
        let dataSaver = UserDefaults(suiteName: TimeGroupName)
        if let data = dataSaver?.data(forKey: TimWidgetKey), let model: MyWidgetsModel = TimData.decodeModel(from: data) {
            return model
        } else {
            return nil
        }
    }

    func appendMyWidgets(itemModel: MyWidgetItemModel, complete: (MyWidgetsModel?) -> Void) {
        let dataSaver = UserDefaults(suiteName: TimeGroupName)
        if var model: MyWidgetsModel = fetchMyWidgets() {
            // 更新数据
            model.datas.append(itemModel)
            // 转换data
            if let newData = TimData.codeModel(from: model) {
                /// 保存data
                dataSaver?.set(newData, forKey: TimWidgetKey)
                complete(model)
            } else {
                complete(nil)
            }

        } else {
            /// 创建新模型
            let model = MyWidgetsModel(datas: [itemModel])
            /// 保存model
            if let data = TimData.codeModel(from: model) {
                dataSaver?.set(data, forKey: TimWidgetKey)
                complete(model)
            } else {
                complete(nil)
            }
        }
    }
}
